﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;                                              
using System.Windows.Navigation;
using System.Windows.Shapes;
using DataLayer;
using System.Xml;
using AvalonDock;
using System.IO;
using System.Windows.Interop;
using System.Windows.Forms;
using wpf = System.Windows.Controls;
using System.Windows.Threading;
using System.Threading;

using NetworkUI;
namespace LuanVanProject
{
    /// <summary>
    /// Interaction logic for MainWindow.xamlProperties.Settings.Default.uEdge
    /// </summary>
    public partial class MainWindow : Window
    {
        #region Variable use for UI region
        //Use for resize word control
        public IList<string> ListTitle;
        MindMap currentMindmap = null;
        MindMap ExportMindmap=null;
        
        DispatcherTimer dispatcherTimer = new DispatcherTimer();
        int percent = 0;
        System.Threading.Thread progressBarThread;
        #endregion Variable use for UI
        //Find Childer with specific Name
        #region Theme and Layout
        private void SaveLayout(object sender, RoutedEventArgs e)
        {
            dockManager.SaveLayout(App.ProjectDirectory + "//" + "SystemFile" + "//" + "layout.xml");
        }

        private void RestoreLayout(object sender, RoutedEventArgs e)
        {
            try
            {
                if (File.Exists(App.ProjectDirectory + "//" + "SystemFile" + "//" + "layout.xml"))
                {
                    dockManager.RestoreLayout(App.ProjectDirectory + "//" + "SystemFile" + "//" + "layout.xml");
                }
            }
            catch (Exception err)
            {

            }

        }
        private void SetDefaultTheme(object sender, RoutedEventArgs e)
        {
            ThemeFactory.ResetTheme();
        }

        private void ChangeCustomTheme(object sender, RoutedEventArgs e)
        {
            string uri = (string)((wpf.MenuItem)sender).Tag;
            ThemeFactory.ChangeTheme(new Uri(uri, UriKind.RelativeOrAbsolute));
        }

        private void ChangeStandardTheme(object sender, RoutedEventArgs e)
        {
            string name = (string)((wpf.MenuItem)sender).Tag;
            ThemeFactory.ChangeTheme(name);
        }

        private void ChangeColor(object sender, RoutedEventArgs e)
        {
            ThemeFactory.ChangeColors((Color)ColorConverter.ConvertFromString(((wpf.MenuItem)sender).Header.ToString()));
        }
        #endregion
        #region Window Event
        public MainWindow()
        {
            InitializeComponent();
            KeyboardManager.WindowHandle = new WindowInteropHelper(this).Handle;
            dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
            dispatcherTimer.Start();
        }
        void MainWindow_Resize(object sender, EventArgs e)
        {
            (sender as WordViewer).Reactive();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            App.ErrorPanel = this.ErrorPanel;
            ErrorDockable.ToggleAutoHide();
            App.mainWindow = this;
            //App.InfoLabel = this.InfoLabel;
            string uri = "/AvalonDock.Themes;component/themes/ExpressionDark.xaml";
            App.projWindow = new ProjectWindow();
            ThemeFactory.ChangeTheme(new Uri(uri, UriKind.RelativeOrAbsolute));
            App.DockPane = this.DockPane;
            App.dockManager = this.dockManager;
            KeyboardManager.mainWindow = this;
            StartUp startUpWin = new StartUp();
            startUpWin.ShowDialog();
            KeyboardManager.WindowHandle = new WindowInteropHelper(this).Handle;
            switch (startUpWin.myResult)
            {
                case 0:
                    Create_Project_Event(null, null);
                    break;
                case 1:
                    Open_Project_Event(null, null);
                    break;
                case 2:
                    App.ProjectDirectory = startUpWin.FileName;
                    Open_Project(startUpWin.FileName);
                    break;
                default:
                    break;
            }
        }
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {

            try
            {
                XmlDocument doc = new XmlDocument();

                if (System.IO.File.Exists( "./RecentProject.xml"))
                {
                    doc.Load("./RecentProject.xml");
                }
                else
                {
                    XmlNode tnode = doc.CreateElement("ProjectList");
                    doc.AppendChild(tnode);
                }
                //Save this project as Currentproject
                if (App.ProjectDirectory != "")
                {
                    XmlNode node = doc.CreateElement("Project");
                    node.InnerText = App.ProjectDirectory + "\\" + "workspace.xml";

                    if (!utility.IsExisted(doc.FirstChild.ChildNodes, node))
                    {
                        doc.FirstChild.AppendChild(node);
                    }
                    if (doc.FirstChild.ChildNodes.Count >= 10)
                    {
                        doc.RemoveChild(doc.FirstChild.FirstChild);
                    }
                    doc.Save("./RecentProject.xml");
                }

                SaveProject();
                DocumentContainForViewer.ClosePPT();
                SaveLayout(null, null);
            }
            catch (Exception er)
            {
                //System.Windows.MessageBox.Show(er.Data.ToString());
            }
            finally
            {

                App.Current.Shutdown();
            }
        }
        void SaveProject()
        {
            // Save Current Mindmap
            currentMindmap.MindmapToXmlDoc(App.ProjectDirectory + "\\" + "Mindmaps" + "\\" + "mindmap.xml");
            foreach (ProjectPane.MindmapTag tag in App.exportMindmapList)
            {
                tag.mindmap.MindmapToXmlDoc(tag.path);
            }

            //reset windows
            //WindowsHelper.GetInstance().Reset();
            WindowsHelper.GetInstance().save();
            //Save Current Openned tab
            //MyProjectPane.SaveCurrentTab();
            ResourcesHelper.Save();
        }
        #endregion
        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
           // CommandManager.InvalidateRequerySuggested();
            ProgressBarCompute();
        }
        void dispOp_Completed()
        {            
            progressBar1.Value = 0;
            percent = 0;
            progressBar1.Visibility = System.Windows.Visibility.Hidden;
            //***App.Synchronize();
        }
        void item_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            DocumentContent docContent = sender as DocumentContent;
            (((docContent).Content as System.Windows.Forms.Integration.WindowsFormsHost).Child as WordViewer).Reactive();
        }

        public void ReceiveHook()
        {
            if (KeyboardManager.returnImageContent != null)
            {
                currentMindmap.RootNode.AddContent( KeyboardManager.returnImageContent);
                TreeViewItemWithIcons treeViewItem = new TreeViewItemWithIcons();
                //***App.Synchronize();
            }
        }
   
     /*
        void item_MouseUp(object sender, MouseButtonEventArgs e)
        {
            TreeViewItem item = sender as TreeViewItem;
            TreeItemHandler handler = item.Tag as TreeItemHandler;
            if (handler.DocContent != null && handler.DocContent.Parent != null)
            {            
                (handler.DocContent.Parent as DocumentPane).SelectedItem= handler.DocContent;
                 if(utility.EqualsExtend( System.IO.Path.GetFileName(handler.FileName),"doc")||(utility.EqualsExtend( System.IO.Path.GetFileName(handler.FileName),"docx")))
                 {
                   ((handler.DocContent.Content as System.Windows.Forms.Integration.WindowsFormsHost).Child as WordViewer).Reactive();
                 }
            }
        }*/
        private void DockablePane_Loaded(object sender, RoutedEventArgs e)
        {
            if (App.activated == false)
            {
                (sender as DockablePane).Visibility = Visibility.Hidden;
            }
        }
        void item_DoubleClick(object sender, MouseButtonEventArgs e)
        {
            TreeViewItem item= sender as TreeViewItem;
            TreeItemHandler handler = item.Tag as TreeItemHandler;
            if (handler.DocContent == null)
            {
                
                dockManager.MainDocumentPane= DockPane;
                handler.DocContent=DocumentContainForViewer.OpenFile(handler.FileName );
                item.Tag = handler;
                DockPane.Items.Add(handler.DocContent);
                DockPane.SelectedItem = handler.DocContent;
                handler.DocContent.Tag = item;
                handler.DocContent.Closing += new EventHandler<System.ComponentModel.CancelEventArgs>(DocContent_Closing);
            }
        }
        void DocContent_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            DocumentContent dc = sender as DocumentContent;
            TreeViewItem tvi=dc.Tag as TreeViewItem;
            TreeItemHandler handler= tvi.Tag as TreeItemHandler;
            handler.DocContent = null;
        }
       
   
        #region project region
        void OpenFileCommand()
        {
            System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            openFileDialog1.Multiselect = false;
            openFileDialog1.Filter = "Supported Files(PDF;DOC;DOCX;PPTX)|*.PDF;*.DOCX;*.PPTX;*.PPT;*.DOC";
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string fileName = openFileDialog1.FileName;
                DocumentContainForViewer doc = DocumentContainForViewer.OpenFile(fileName);
                this.DockPane.Items.Add(doc);
            }
        }
        /// <summary>
        /// Create New Project File And Folder
        /// </summary>
        /// <param name="fileName"></param>
        void CreateProjectFile(string fileName)
        {
            System.IO.Directory.CreateDirectory(fileName);
            System.IO.Directory.CreateDirectory(fileName + "\\" + "SystemFile");
            System.IO.Directory.CreateDirectory(fileName + "\\" + "Images");
            ResourcesHelper.CreateNewResourceFile(fileName + "\\" + "SystemFile");
            System.IO.Directory.CreateDirectory(fileName + "\\" + "Mindmaps");
            System.IO.Directory.CreateDirectory(fileName + "\\" + "Outputs");
            System.IO.Directory.CreateDirectory(fileName + "\\" + "Documents");
            WindowsHelper.CreateWorkSpaceFile(fileName);
        }
        /// <summary>
        /// Handling the create project event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Create_Project_Event(object sender, RoutedEventArgs e)
        {
            DockPane.Items.Clear();
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "New Project Dialog";
            sfd.Filter = "Project Folder |*|All Files (*.*)|*.*";
            sfd.FilterIndex = 1;
           if( sfd.ShowDialog()==System.Windows.Forms.DialogResult.OK  )
            {
              //Create new file
               CreateProjectFile(sfd.FileName);
               //Assign Data to control
               App.ProjectDirectory = sfd.FileName;
               currentMindmap = new MindMap();
               currentMindmap.RootNode.Name = System.IO.Path.GetFileName(sfd.FileName);
               currentMindmap.RootNode.Name = System.IO.Path.GetFileName(sfd.FileName);
               currentMindmap.MindmapToXmlDoc(App.ProjectDirectory + "\\" + "Mindmaps" + "\\" + "mindmap.xml");
               Open_Project(sfd.FileName+"\\" + "Workspace.xml");
            }
        }
     
        private void Open_Project_Event(object sender, RoutedEventArgs e)
        {
            DockPane.Items.Clear();
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (System.IO.Path.GetFileName(openFileDialog1.FileName).ToLower().Equals("workspace.xml"))
                {
                    Open_Project(openFileDialog1.FileName);
                }
                else
                {
                    System.Windows.MessageBox.Show("Please choose workspace.xml file");
                }
            }
        }

        void Open_Project(string a_filename)
        {
            DockPane.Items.Clear();
            string folderName = System.IO.Path.GetDirectoryName(a_filename);
            if (System.IO.File.Exists(a_filename))
            {
                //try
                {
                    App.ProjectDirectory = folderName;

                    App.DockPane = DockPane;
                    App.DockPane.Items.Clear();
                    MyProjectPane.PrepareSystemFile();
                    App.projWindow.ProjectPane.PrepareSystemFile();
                    this.dockPane.Visibility = Visibility.Visible;
                    App.activated = true;
                    DockPane.Visibility = Visibility.Visible;
                    NodePane.Visibility = Visibility.Visible;
                    currentMindmap = new MindMap(App.ProjectDirectory + "\\" + "Mindmaps" + "\\mindmap.xml");
                    App.currentMindmap = currentMindmap;
                    TreeViewItemWithIcons.PrepareArgument(MyProjectPane._NodeTree, currentMindmap, DetailView);
                    App.DetailView = DetailView;
                    MyProjectPane.PrepareNodeTree();
                    App.projWindow.ProjectPane.PrepareNodeTree();
                    MyProjectPane.Prepare_Project_Pane();
                    App.projWindow.ProjectPane.Prepare_Project_Pane();
                    DetailViewContent.dockPane = this.DockPane;
                    DetailViewContent.proPane = this.MyProjectPane;
                    MindmapEditor.detailView = DetailView;
                    TreeViewItemWithIcons.dockPane = DockPane;
                    
                    DetailView.SetUpComboBox();
                    this.Title = currentMindmap.RootNode.Name;
                }
               /* catch {
                    System.Windows.MessageBox.Show("Mind Map file is invalid, please try it again");
                    this.Close();
                }*/
            }
            else
            {
                System.Windows.MessageBox.Show("File isn't existed");
            }
        }

        void ProgressBarCompute()
        {
            progressBarThread = new Thread(
                    new ThreadStart(
                        delegate()
                        {
                            DispatcherOperation dispOp =
                                progressBar1.Dispatcher.BeginInvoke(DispatcherPriority.Loaded,
                                new Action(
                                    delegate()
                                    {
                                        progressBar1.Value = percent;
                                        if (progressBar1.Visibility == System.Windows.Visibility.Hidden && progressBar1.Value > 1)
                                        {
                                            progressBar1.Visibility = System.Windows.Visibility.Visible;
                                        }
                                        if (progressBar1.Value == 100)
                                        {                                            
                                            dispOp_Completed();
                                        }
                                    }
                                    ));
                            // dispOp.Completed += new EventHandler(dispOp_Completed); 
                        }
                        ));
            progressBarThread.Start(); 
        }
        #endregion project region

        #region Menu Event Handling region

        private void Close_Event(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        private void Help_Click(object sender, RoutedEventArgs e)
        {

        }
        private void About_Click(object sender, RoutedEventArgs e)
        {
            About aboutWindow = new About();
            aboutWindow.Show();
        }

        /// <summary>
        /// Call web browser
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CallWebBrowser(object sender, RoutedEventArgs e)
        {
            WebControl webControl = new WebControl();
            DocumentContent docContent = new DocumentContent();
            docContent.Title = "Web Browser"; ;
            docContent.Content = webControl;
            DockPane.Items.Add(docContent);
        }
        #endregion Menu Event Handling        

        private void ComboBoxItem_SelectedExpandMode(object sender, RoutedEventArgs e)
        {
            try
            {
                NodePaneContent.ToggleAutoHide();
                Document_Pane.ToggleAutoHide();
            }
            catch { }

        }

        private void ComboBoxItem_SelectedNormalMode(object sender, RoutedEventArgs e)
        {
            NodePaneContent.Width = 240;
            NodePaneContent.Show();
            Document_Pane.Width = 320;
            Document_Pane.Show();
        }

        private void ComboBoxItem_Selected_GlobalMode(object sender, RoutedEventArgs e)
        {
            App.ShowProjectWindows();

        }
        /// <summary>
        /// 0 for Expand
        /// 1 for Global
        /// 2 for Normal
        /// 
        /// </summary>
        /// <param name="selectIndex"></param>
        public void SetMode(int selectIndex)
        {
            ComboLayout.SelectedIndex = selectIndex;
        }
        private void DockPane_Unloaded(object sender, RoutedEventArgs e)
        {
           /* System.Windows.MessageBox.Show("Unload");
            DocumentPane newDockPane = new DocumentPane();
            (App.DockPane.Parent as ResizingPanel).Children.Add(newDockPane);
            App.DockPane = new DocumentPane();*/

        }
        string fileName = "";
        private void Import_Event(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog dlgOpen = new OpenFileDialog();
            dlgOpen.Filter = "Supported Files(PPT;PPTX)|*.PPTX;*.PPT";
            System.Windows.Forms.DialogResult rs = dlgOpen.ShowDialog();
            if (rs == System.Windows.Forms.DialogResult.OK)
            {
                fileName = dlgOpen.FileName;
                Thread t = new Thread(new ThreadStart(
                ConvertPPT2MindMap));
                t.Start();
            }
        }
        void ConvertPPT2MindMap()
        {
            try
            {
                if (currentMindmap == null)
                {
                    System.Windows.MessageBox.Show("Please open a project before using import feature");
                }
                else
                {
                    MindMap map = Converter.PP2Mindmap(fileName, ref percent, App.ProjectDirectory);
                    List<Node> existNodes = new List<Node>();
                    currentMindmap.GetListNode(existNodes);
                    map.CheckAndChangeNodesName(existNodes);
                    currentMindmap.RootNode.AddNode(map.RootNode);
                }
            }
            catch
            {
                System.Windows.MessageBox.Show("Import process occur errors, probably because your computer is not installed Microsoft Powerpoint, please install the 2007 version and try again");
            }
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            SaveProject();
        }

    }
}
